<?php
namespace Todo\Model\Rate;

use Todo\Model\BaseModel;
use Todo\Service\UserService;

class UserModel extends BaseModel
{
    public $tableName = 'rate_user';

    public $_validate = array(
        array('user_id', 'require', '请选择用户'),
        array('project_id', 'require', '请选择项目'),
        array('type', 'require', '请选择参与类型')
    );

    protected $_auto = array(
        array('name', '_name', self::MODEL_BOTH, 'callback'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );
    
    protected function _name(){
        $name = I('post.name');
        if(!$name) return $name;
        return D('Todo/Sys/User')->keyFind(I('post.user_id'), 'nickname');
    }

    /**
     * 导入一行数据
     * @param $row 数据
     * @param int $exists=1 数据冲突处理方式：1报错，2跳过，3覆盖
     * @return bool
     */
    public function importOne($row, $exists=1){
        if(count($row) < 2 || !$row[0] || !$row[1]){
            $this->error = "姓名、工号（学号）不能为空";
            return false;
        }
        $data = array(
            'project_id' => I('post.project_id'),
            'type' => I('post.type'),
            'tnt_id' => auto_tnt()
        );
        if(I('post.user_type') == '1'){ //老师
            $identity = 'teacher';
            $this->error = "老师(".$row[0].",".$row[1].")不存在";
        }else if(I('post.user_type') == '2'){ //学生
            $identity = 'student';
            $this->error = "学生(".$row[0].",".$row[1].")不存在";
        }else{
            $identity = null;
            $this->error = "用户(".$row[0].",".$row[1].")不存在";
        }

        $info = UserService::getInstance()->checkImportUser(trim($row[1]), trim($row[0]), $identity);
        if(!$info){
            return false;
        }
        $data['user_id'] = $info['id'];
        $data['name'] = $info['nickname'];
        $old = $this->where($data)->find();
        if(!$old){
            return $this->add($data);
        }
        return true;
    }
}